package com.yejq.db;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.Writer;
import java.net.Socket;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.yejq.Constants;

public class BingbingDbdProcessor implements Processor {

	private Socket socket;

	private Logger logger = LoggerFactory.getLogger(getClass());

	public BingbingDbdProcessor() {
	}

	public BingbingDbdProcessor(Socket socket) {
		this.socket = socket;
	}

	public void run() {
		Reader reader = null;
		Writer writer = null;
		try {
			while (true) {
				reader = new InputStreamReader(socket.getInputStream());
				char chars[] = new char[64];
				int len;
				StringBuilder command = new StringBuilder();
				String temp;
				int index;
				while ((len = reader.read(chars)) != -1) {
					temp = new String(chars, 0, len);
					if ((index = temp.indexOf(Constants.EOF)) != -1) {// 遇到eof时就结束接收
						command.append(temp.substring(0, index));
						break;
					}
					command.append(temp);
				}
				logger.info("from client command: {}", command);
				// 读完后写一句
				writer = new OutputStreamWriter(socket.getOutputStream());
				writer.write("Hello Client.");
				writer.write(Constants.EOF);
				writer.flush();
				
				if (command.toString().equalsIgnoreCase(Constants.QUIT)) {
					break;
				}
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

}
